from django.shortcuts import render, get_object_or_404
# django便捷函数shortcuts https://docs.djangoproject.com/zh-hans/4.0/topics/http/shortcuts/#module-django.shortcuts
from django.http import HttpResponse,Http404,HttpResponseRedirect
from django.template import loader
from .models import Question, Choice
from django.urls import reverse
# 通用视图
from django.views import generic
from django.utils import timezone
# Create your views here.

from django.http import HttpResponse


class DetailView(generic.DetailView):
    model = Question
    # 默认情况下，通用视图 DetailView 使用一个叫做 <app name>/<model name>_detail.html 的模板。
    # 在我们的例子中，它将使用 "polls/question_detail.html" 模板。
    # template_name 属性是用来告诉 Django 使用一个指定的模板名字，而不是自动生成的默认名字。
    template_name = 'polls/detail.html'

    def get_queryset(self):
        """
        Excludes any questions that aren't published yet.
        """
        return Question.objects.filter(pub_date__lte=timezone.now())


'''
def detail(request, question_id):
    # 尝试用 get() 函数获取一个对象，如果不存在就抛出 Http404 错误也是一个普遍的流程。Django 也提供了一个快捷函数get_object_or_404
    question = get_object_or_404(Question, pk=question_id)
    return render(request, 'polls/detail.html', {'question': question})
'''


class ResultsView(generic.DetailView):
    model = Question
    template_name = 'polls/results.html'


'''
def results(request, question_id):
    question = get_object_or_404(Question, pk=question_id)
    return render(request, 'polls/results.html', {'question': question})
'''


def vote(request, question_id):
    question = get_object_or_404(Question, pk=question_id)
    try:
        selected_choice = question.choice_set.get(pk=request.POST['choice'])
    except (KeyError, Choice.DoesNotExist):
        # Redisplay the question voting form.
        return render(request, 'polls/detail.html', {
            'question': question,
            'error_message': "You didn't select a choice.",
        })
    else:
        selected_choice.votes += 1
        selected_choice.save()
        # Always return an HttpResponseRedirect after successfully dealing
        # with POST data. This prevents data from being posted twice if a
        # user hits the Back button.
        #  reverse() 函数。这个函数避免了我们在视图函数中硬编码 URL。它需要我们给出我们想要跳转的视图的名字和该视图所对应的 URL 模式中需要给该视图提供的参数。
        return HttpResponseRedirect(reverse('polls:results', args=(question.id,)))


class IndexView(generic.ListView):
    template_name = 'polls/index.html'
    context_object_name = 'latest_question_list'

    def get_queryset(self):
        # 最近五天但是不包含未来的,__lte 小于等于（django orm筛选）
        return Question.objects.filter(pub_date__lte=timezone.now()).order_by('-pub_date')[:5]
        # 最近五天的
        # return Question.objects.order_by('-pub_date')[:5]


'''
def index(request):
    latest_question_list = Question.objects.order_by('-pub_date')[:5]
# 载入模板，填充上下文，再返回由它生成的 HttpResponse 对象」是一个非常常用的操作流程。于是 Django 提供了一个快捷函数render（）
    context = {'latest_question_list': latest_question_list}
    return render(request, 'polls/index.html', context)

'''
